<?php
namespace app\controller;

use app\BaseController;
use think\facade\Db;
use think\facade\Request;
use RtcTokenBuilder2;
use Kreait\Firebase\Factory;
use Kreait\Firebase\Messaging\CloudMessage;

class Push extends BaseController {
    public function index() {
        try {
            $token = Request::header('Authorization');
            if (empty($token) || !preg_match('/^Bearer\s+(.+)$/i', $token, $matches)) {
                return json(['code' => 401, 'msg' => '未授权访问']);
            }

            $token = $matches[1];
            $sender = Db::name('think_users')->where('token', $token)->find();
            if (!$sender) {
                return json(['code' => 401, 'msg' => 'token无效']);
            }
            // 获取请求中的参数
            $messageData = Request::post("message"); // 获取 message JSON 字符串
            $receiverId = Request::post("receiver_id"); // 获取接收者的 FCM 令牌

            if (empty($messageData) || empty($receiverId)) {
                return json(['code' => 400, 'msg' => '参数缺失']);
            }
            // 从数据库中查询 receiver_token
            $receiver = Db::name('think_users')->where('user_number', $receiverId)->find();
            if (!$receiver || empty($receiver['token'])) {
                return json(['code' => 404, 'msg' => '接收者不存在或未配置 FCM 令牌', 'id'=>$receiverId]);
            }
            $receiverToken = $receiver['apns_token'];

            // // 将 JSON 字符串解析为数组
            // $messageData = json_decode($messageJson, true);

            // 初始化 Firebase Messaging
            $factory = (new Factory)
                ->withServiceAccount(__DIR__ . '/../../thirdparty/fcm/fcm.json'); // 替换为实际路径
            $messaging = $factory->createMessaging();
            // 构建 FCM 消息
            $message = CloudMessage::fromArray([
                'token' => $receiverToken, // 接收者的 FCM 令牌
                'notification' => [
                    'title' => $messageData['senderNickname'] ?? '通知标题',
                    'body' => $messageData['textElem']['content'] ?? '通知内容',
                ],
                'apns' => [
                    'payload' => [
                        'aps' => [
                            'mutable-content' => 1, // 设置 content-available
                        ],
                        "avatar"=>$sender['avatar'],
                        "type"=>"send_message"
                    ],
                ],
            ]);

            // 发送消息
            $messaging->send($message);
            return json(['code' => 200, 'msg' => $messageData]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '消息发送失败', 'error' => $e->getMessage()]);
        }
    }
}